<template>
    <div class="e-form">
        <BillTop  @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="盘点明细"
                    name="detailed"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="basicForm"
                                :label-width="formLabelWidth"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="盘点编号：">
                                            <span>{{ basicForm.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                            <span>{{ basicForm.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="业务类型">
                                            <span>
                                                {{
                                                    businessTypeValue(
                                                        basicForm.businessTypeKey
                                                    )
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="盘点日期：">
                                            <span>
                                                {{ basicForm.inventoryDate }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="分包商：">
                                            <span>
                                                {{
                                                    basicForm.subcontractorName
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="盘点人员：">
                                            <span>
                                                {{ basicForm.inventoryCreator }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="合同名称：">
                                            <span>{{
                                                basicForm.contractName
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="仓库：">
                                            <span>{{
                                                basicForm.warehouseName
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>
                                                {{
                                                    statusLable(basicForm.state)
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注：">
                                            <span>
                                                {{ basicForm.remarks }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row v-if="basicForm.redState !== -1">
                                    <el-col :span="12">
                                        <!-- 仅发生冲红单业务时,才显示该字段,暂未做判断 -->
                                        <el-form-item label="冲红单">
                                            <span :style="redBillStateStyle">{{
                                                redBillStateFun
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="basicForm.state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{
                                                basicForm.nullifyCreator
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{
                                                basicForm.nullifyReason
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="basicForm.state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废说明：">
                                            <span>{{
                                                basicForm.nullifyDescription
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废时间：">
                                            <span>{{
                                                basicForm.nullifyCreated
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>
                    <!-- 盘点明细 -->
                    <div id="detailedCon" class="con">
                        <div class="tabs-title" id="detailed">盘点明细</div>
                        <div class="e-table">
                            <div class="errorMsg" v-if="errorMsg.length > 0">
                                <span
                                    v-for="(item, index) in errorMsg"
                                    :key="index"
                                >
                                    {{ item }}
                                </span>
                            </div>
                            <el-table
                                class="table"
                                :data="detailedTableData"
                                border
                                style="width: 100%"
                                default-expand-all
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                ref="multipleTable"
                                row-key="uuid"
                                :max-height="$store.state.tableHeight"
                                :row-class-name="tableRowClassName"
                                 v-sortTable="{ 'tableData': detailedTableData, '_this': this, 'ref': 'multipleTable' }"
                            >
                                <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="warehouseName"
                                    label="仓库"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="subItem"
                                    label="分部分项"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="bookQuantity"
                                    label="账面数量"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="inventoryQuantity"
                                    label="实盘数量"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <div v-if="$index > 0">
                                            <el-input
                                                v-model="row.inventoryQuantity"
                                                v-if="!isRedSingle"
                                                @input="curStateChange(row)"
                                            ></el-input>

                                            <span v-else>
                                                {{ row.inventoryQuantity }}
                                            </span>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="expendQuantity"
                                    label="耗用数量"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <span v-if="$index > 0">
                                            {{ row.expendQuantity }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="type"
                                    label="类型"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <div v-if="$index > 0">
                                            <el-select
                                                v-if="!isRedSingle"
                                                v-model="row.type"
                                            >
                                                <el-option
                                                    :value="0"
                                                    label="工程消耗"
                                                ></el-option>
                                                <el-option
                                                    :value="1"
                                                    label="研发支出"
                                                ></el-option>
                                                <el-option
                                                    :value="2"
                                                    label="安全环保支出"
                                                ></el-option>
                                            </el-select>
                                            <span v-else>
                                                <span>{{ row.type }}</span>
                                            </span>
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">照片信息</div>
                        <attach-comp
                            isView
                            :relationId="attachId"
                            bucketName="turnover"
                        />
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :billType="6074"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <el-button
                type="primary"
                style="background: #2e61d7"
                v-if="
                    basicForm.state == 2 &&
                    basicForm.redState < 1 &&
                    basicForm.isAmortization == 0
                "
                @click="redSingle"
                >冲红单</el-button
            >
            <ComExaButtons
                :auditState="auditState"
                :state="basicForm.state"
                @exas="exas"
                :founderId="basicForm.founderId"
            />
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import AttachComp from '@/components/common/attachIndex'
import auditRequest from '@/api/turnover/audit.js'
import { doChildren } from '@/api/turnover/utils.js'
import otherRequest from '@/api/turnover/other.js'
// import { getUuid } from '@/utils/common'
import { getUuid } from '@/utils/common'
import { exas } from '@/pages/revolveMaterialManage/common/revolveCom.js'

import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'
import ComExaButtons from '@/components/common/exaButtons'
import { mapMutations } from 'vuex'

import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'

export default {
    components: {
        ComExaButtons,
        AttachComp,
        ComAuditHistoryIndex
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value === param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },

        businessTypeValue () {
            return param => {
                const obj = this.businessType.find(x => x.id == param)
                if (obj !== undefined) {
                    return obj.uname
                }
            }
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.basicForm.redState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        'basicForm.redState' () {
            if (this.basicForm.redState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.basicForm.redState == 0 ||
                this.basicForm.redState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.basicForm.redState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        }
    },
    mounted () {
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'detailed', 'attach', 'auditHistory']
        this.tabArr = arr //标星星

        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    created () {
        this.billId = this.$route.query.billid

        this.getBasicInfo()
        this.getCurrentUnitInfo()
        this.getDtlList()
    },
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            basicForm: {
                billId: '',
                billNo: '',
                businessTypeKey: '',
                businessTypeValue: '',
                contractId: '',
                contractName: '',
                contractNo: '',
                inventoryCreator: '',
                inventoryCreatorId: '',
                inventoryDate: '',
                isRed: 0,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                parentId: '',
                remarks: '',
                state: 0,
                subcontractorId: '',
                subcontractorName: '',
                warehouseId: '',
                warehouseName: ''
            },
            query: {
                limit: 10,
                number: '',
                orgname: '',
                page: 1,
                states: []
            },
            formLabelWidth: '150px',
            detailedTableData: [], //物资明细
            changeTableData: [], //变更信息
            basicInfo: {},
            stateArr: ['草稿', '审核中', '已审核', '已作废'],
            MouseEnterId: 0,
            isSkip: false, //是否跳转
            auditState: {},
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6074,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            nullifyParams: {
                //作废
                billId: this.$route.query.billid,
                billType: 6074,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: ''
            },
            isRedSingle: false,
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },

            businessType: [
                {
                    id: '1',
                    uname: '分包合同'
                },
                {
                    id: '2',
                    uname: '加工合同'
                },
                {
                    id: '3',
                    uname: '销售合同'
                },
                {
                    id: '4',
                    uname: '事实合同'
                },
                {
                    id: '5',
                    uname: '自行加工'
                }
            ],
        }
    },
    methods: {
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight =
                        document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },

        getBasicInfo () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/inventory/findById',
                    params: {
                        billId: this.billId
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    res.redState === 3
                        ? (this.isRedSingle = true)
                        : (this.isRedSingle = false)

                    this.basicForm = res
                })
        },
        getDtlList () {
            otherRequest.turnoverInventoryGetDtlList(this.billId).then(res => {
                console.log(res, 'res')
                if (res.length > 0) {
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.businessType = this.basicForm.businessTypeKey

                        item.children.forEach(i => {
                            i.parentId = item.uuid
                            i.uuid = i.dtlId
                            i.changeType = 0
                        })

                        const count = item.children.reduce(
                            (prev, c) => (prev += c.amount || 0),
                            0
                        )
                        item.materialName = `小计： ${count}`
                    })

                    this.detailedTableData = res
                    console.log(res, 'res')
                }
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                otherRequest
                    .turnoverInventoryUpdate(this.basicForm)
                    .then(() => {
                        this.getBasicInfo() //更新基本信息
                        resolve()
                    })
                    .catch(err => {
                        this.setError('baseInfo')
                        reject(err)
                    })
            })
        },
        //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject) => {
                this.verifyTable()
                    .then(() => {
                        otherRequest
                            .turnoverInventoryUpdateDtl(this.detailedTableData)
                            .then(() => {
                                this.getDtlList() //更新明细
                                resolve()
                            })
                            .catch(err => {
                                this.setError('detailed')
                                reject(err)
                            })
                    })
                    .catch(err => {
                        this.setError('detailed')
                        reject(err)
                        this.scorllError()
                    })
            })
        },
        /**
         * 下边几个按钮
         */
        async exas (arg) {
            const requestFn = () => {
                return [this.updateBaseInfo(), this.updateBudgetDtl()]
            }
            exas(arg, this, requestFn)
        },
        // 审核相关操作
        ...mapMutations(['setAuditParams']),
        // 点击冲红单
        redSingle () {
            this.$router.replace({
                path: '/revolveInventoryAdd',
                query: { isRedSingle: '1', billid: this.billId }
            })
        },

        handleClose () {
            this.$router.push('/revolveInventoryList')
        },
        clickAddDetaild () {
            const data = [
                {
                    billId: null,
                    billNo: 'SRBGZCNZDD20220126001',
                    dtlId: '1500729760934457314',
                    id: '1486168294460231681',
                    materialClassId:
                        '1500727756765982722/1500729232783503361/1500729509653704706',
                    materialClassName: '周转材料/型材及管材/花纹钢板',
                    materialId: '1500729760934457345',
                    materialName: '花纹钢板',
                    name: '四川公路桥梁建设集团有限公司',
                    notWarehosingQuantity: 11,
                    parentId: '1439990097591140358',
                    quantity: 12,
                    spec: '321',
                    texture: '213',
                    unit: '321',
                    isDetailed: 1,
                    paperQuantity: 10
                }
            ]
            this.detailedTableData = doChildren(data, 'Inventory', this.billId)
        },
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            if (row.changeType !== 1) {
                {
                    row.changeType = 2
                }
            }

            // 计算剩余库存数量
            if (row.paperQuantity && row.inventoryQuantity) {
                row.expendQuantity =
                    parseFloat(row.paperQuantity) -
                    parseFloat(row.inventoryQuantity)
            }
        },
        //点击删除的时候
        deleteEle (row) {
            row.changeType = -1
        },
        // 处理树
        tableRowClassName ({ row }) {
            if (row.children) {
                return 'warning-row'
            } else if (row.changeType === -1) {
                return 'row-hide'
            } else {
                return 'row-show'
            }
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //跳转到明细
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //计划明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                this.detailedTableData.forEach(v => {
                    v.children.forEach((item, index) => {
                        if (item.changeType !== -1) {
                            if (
                                item.inventoryQuantity === '' ||
                                item.inventoryQuantity === null
                            ) {
                                let str = `请填写第 ${index + 1} 行的实盘数量`
                                this.errorMsg.push(str)
                            }
                            if (item.type === '' || item.type === null) {
                                let str = `请填写第 ${index + 1} 行的类型`
                                this.errorMsg.push(str)
                            }
                        }
                    })
                })

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}
::v-deep.el-table .cell {
    text-align: center;
}
#iconEdit:hover {
    color: blue;
}

.like {
    color: rgb(46, 97, 215);
    font-size: 17px;
    line-height: 30px;
    cursor: pointer;
}
</style>
